package com.example.smartf.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisUtils {
    //日志记录器
    Logger logger = LoggerFactory.getLogger(getClass());

    private RedisTemplate<String,Object> redisTemplate;
    private static RedisUtils redisUtils;

    private RedisUtils(){}
    public static RedisUtils getInstance(){
        if(redisUtils == null){
            redisUtils = new RedisUtils();
        }
        return redisUtils;
    }

    public  void setRedisTemplate(RedisTemplate<String,Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    //查询是否存在key
    public boolean hasKey(String key){
        try{
            logger.info("查询redis：" + key + " 查询成功！");
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            logger.warn("查询redis：" + key + " 查询错误！");
            e.printStackTrace();
            return false;
        }
    }

    //读取缓存
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    //写入缓存
    public boolean set(String key, Object value){
        boolean result = false;
        try{
            redisTemplate.opsForValue().set(key,value);
            logger.info("写入redis：" + key + "成功！");
            result = true;
        }catch (Exception e){
            logger.warn("写入redis：" + key + " 失败！");
            e.printStackTrace();
        }
        return result;
    }

    //设置指定key 超时时间
    public boolean expire(String key, long time){
        try{
            if(time > 0){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
                logger.info("设置redis超时时间：" + key + "成功！");
            }
            return true;
        }catch (Exception e){
            logger.warn("设置redis超时时间：" + key + "失败！");
            e.printStackTrace();
            return false;
        }
    }

    //更新缓存
    public boolean getAndSet(String key, String value){
        boolean result = false;
        try{
            redisTemplate.opsForValue().getAndSet(key,value);
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    //删除缓存
    public boolean delete(String key){
        boolean result = false;
        try{
            redisTemplate.delete(key);
            logger.info("删除redis：" + key + "成功！");
            result = true;
        }catch (Exception e){
            logger.warn("删除redis：" + key + "失败！");
            e.printStackTrace();
        }
        return result;
    }
}
